namespace Behaving.Composites
{
    /* Always check child nodes from left to right (even if a child returned "running" on the previous tick). If one of the 
    * earlier child nodes returns Success or Running, then cancel the prior running node, otherwise continue running it.
    * From http://www.altdevblogaday.com/2011/02/24/introduction-to-behavior-trees/ */
    public class PriortySelector : Composite
    {
        public PriortySelector(params Behaviour[] children)
            : base(children)
        {
        }

        public override RunningState Execute(BehaviourTree behaviourTree)
        {
            // No need to figure out which (if any) of our children is the running one, 
            // just keep going until we find it and continue if it still wants to go.
            // The regular selector doesn't retest higher priority selectors, it sticks with
            // anyone that keeps returning running.
            for (int i = 0; i < Children.Count; i++)
            {
                Behaviour behaviour = Children[i];

                RunningState runningState = behaviour.Tick(behaviourTree);

                if (runningState == RunningState.Running)
                {
                    return runningState;
                }

                if (runningState == RunningState.Success)
                {
                    return runningState;
                }
            }

            return RunningState.Failure;
        }
    }
}